#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/11/6 12:44
# @Author  : Triste_hui

# 对数据库的操作进行封装
from setting import *
import pymysql
import warnings
import random


class Game:
    # 构造函数
    def __init__(self):
        warnings.filterwarnings('ignore')
        self.conn = None
        self.cur = None

    # 连接数据库
    def connect(self):
        self.conn = pymysql.connect(**DB_CONFIG)
        self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 关闭数据库
    def close(self):
        self.cur.close()
        self.conn.close()

    # 初始化数据表
    def setup(self):
        self.connect()
        SQL = [
            # 创建user表格
            "create table if not exists user(id int(10) PRIMARY KEY AUTO_INCREMENT, name text, gold int(10), diamond int(10), lv int(2), card int(3));",
            "create table if not exists card(id int(4) PRIMARY KEY AUTO_INCREMENT, draw int, name text, quality int(1), base_atk double , base_def double);",
        ]
        for sql in SQL:
            self.cur.execute(sql)
            # print(self.cur.fetchone())
        self.conn.commit()
        self.close()

    # 获取角色信息
    def get_user(self, name):
        self.connect()
        sql = "SELECT * FROM user WHERE name='%s';" % name
        self.cur.execute(sql)
        return self.cur.fetchone()
        self.close()

    # 新建角色
    def new_user(self, name):
        self.connect()
        # 检查角色是否存在
        if not self.get_user(name):
            # 角色不存在,创建角色并赠送10000金币10000钻石
            sql = "INSERT INTO user(name, gold, diamond, lv, card)VALUE ('%s', 10000, 10000, 1, 0);" % name
            self.cur.execute(sql)
            self.conn.commit()
            self.close()
            return True
        else:
            return False

    # 加载卡片
    def load_card(self):
        self.connect()
        for card in CARD_CONFIG:
            name = card.get("name")
            draw = card.get("draw")
            quality = card.get("quality")
            base_atk = card.get("base_atk")
            base_def = card.get("base_def")
            sql = "INSERT INTO card(draw, name, quality, base_atk, base_def) VALUE (%d, '%s', %d, %d, %d);" % (draw, name, quality, base_atk, base_def)
            self.cur.execute(sql)
            self.conn.commit()
        self.close()

    def draw_card(self, q):
        self.connect()
        sql = "SELECT * FROM card WHERE quality=%d AND draw=1;" % q
        self.cur.execute(sql)
        result = random.choice(self.cur.fetchall())
        return result


game = Game()
#game.setup()
#game.load_card()
game.draw_card(1)